<template>
  <div class="club-info-edit">
    <h3 class="section-subtitle">社团基本信息</h3>
    <el-form
      ref="clubInfoFormRef"
      :model="clubInfoForm"
      :rules="clubInfoRules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="社团名称" prop="clubname">
        <el-input v-model="clubInfoForm.clubname" placeholder="请输入社团名称"></el-input>
      </el-form-item>
      <el-form-item label="社团描述" prop="description">
        <el-input
          v-model="clubInfoForm.description"
          type="textarea"
          rows="4"
          placeholder="请输入社团描述"
        ></el-input>
      </el-form-item>
      <el-form-item label="社团Logo" prop="clubimg">
        <el-upload
          action="#"
          :show-file-list="false"
          :before-upload="handleLogoUpload"
          :http-request="() => {}"
          class="logo-uploader"
        >
          <img v-if="logoPreviewUrl" :src="logoPreviewUrl" class="logo" alt="Logo Preview" />
          <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <p class="upload-tip">点击上传新的Logo，支持JPG/PNG格式，大小不超过2MB</p>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存更改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 解散社团按钮区域 -->
    <div class="dissolve-button-container">
        <el-button type="danger" plain @click="handleApplyDissolution">申请解散社团</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const route = useRoute()
const clubId = route.params.id
const loading = ref(false)
const clubInfoFormRef = ref(null)
const logoFile = ref(null) // 存储待上传的 logo 文件
const logoPreviewUrl = ref('') // logo 预览 URL

// 表单数据
const clubInfoForm = reactive({
  clubname: '',
  description: '',
  clubimg: null // 存储当前 logo 的 ID 或 URL
})

// 验证规则
const clubInfoRules = reactive({
  clubname: [{ required: true, message: '请输入社团名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入社团描述', trigger: 'blur' }]
})

// 获取社团当前信息
const fetchClubInfo = async () => {
  loading.value = true
  try {
    const response = await axios.get(`http://localhost:5000/clubs/${clubId}`)
    const data = response.data
    if (data) {
      clubInfoForm.clubname = data.clubname
      clubInfoForm.description = data.description
      clubInfoForm.clubimg = data.clubimg // 存储 logo ID
      if (data.clubimg) {
        logoPreviewUrl.value = `http://localhost:5000/uploads/${data.clubimg}`
      } else {
        logoPreviewUrl.value = '' // 没有 logo
      }
    }
  } catch (error) {
    console.error('获取社团信息失败:', error)
    ElMessage.error('获取社团信息失败')
  } finally {
    loading.value = false
  }
}

// 处理 Logo 上传前的校验
const handleLogoUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  // 预览本地图片
  logoPreviewUrl.value = URL.createObjectURL(file)
  logoFile.value = file // 存储文件待上传
  return false // 阻止 el-upload 的自动上传
}

// 提交表单
const submitForm = () => {
  clubInfoFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const formData = new FormData()
        formData.append('clubname', clubInfoForm.clubname)
        formData.append('description', clubInfoForm.description)
        if (logoFile.value) {
          formData.append('clubimg', logoFile.value) // 添加新的 logo 文件
        }

        const token = localStorage.getItem('token')
        if (!token) {
            ElMessage.warning('请先登录');
            loading.value = false;
            return;
        }

        // 调用更新 API
        await axios.put(`http://localhost:5000/clubs/${clubId}`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${token}` // 如果需要认证
          }
        })

        ElMessage.success('社团信息更新成功');
        logoFile.value = null; // 清除待上传文件
        // 重新获取信息以更新预览
        // await fetchClubInfo(); // 注释掉原有的局部更新逻辑
        location.reload(); // 新增：刷新页面
      } catch (error) {
        console.error('更新社团信息失败:', error)
        ElMessage.error('更新社团信息失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 新增：处理解散申请
const handleApplyDissolution = async () => {
    try {
        const { value: reason } = await ElMessageBox.prompt(
            '请输入解散社团的原因，提交后将由学校管理员审核。此操作需要谨慎！',
            '申请解散社团',
            {
                confirmButtonText: '确认提交申请',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputPlaceholder: '请输入详细的解散原因',
                inputValidator: (value) => {
                    if (!value || value.trim().length === 0) {
                        return '必须填写解散原因';
                    }
                    return true;
                }
            }
        );

        if (reason) {
            loading.value = true;
            const token = localStorage.getItem('token');
            if (!token) {
                ElMessage.warning('请先登录');
                loading.value = false;
                return;
            }

            await axios.post(`http://localhost:5000/clubs/${clubId}/dissolution-applications`,
                { reason },
                {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                }
            );
            ElMessage.success('社团解散申请已提交，请等待管理员审核');
        }
    } catch (error) {
        if (error !== 'cancel') { // 用户点击取消时不报错
            console.error('提交解散申请失败:', error);
            ElMessage.error('提交解散申请失败: ' + (error.response?.data?.message || error.message));
        }
    } finally {
        loading.value = false;
    }
};

// 重置表单
const resetForm = () => {
  logoFile.value = null // 清除待上传文件
  fetchClubInfo() // 重新加载原始数据
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchClubInfo()
})
</script>

<style scoped>
.club-info-edit {
  padding: 20px;
}

.section-subtitle {
  color: #eee;
  font-size: 18px;
  margin-bottom: 20px;
}

/* Logo 上传样式 */
.logo-uploader .logo {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.logo-uploader :deep(.el-upload) {
  border: 1px dashed #444;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.logo-uploader :deep(.el-upload:hover) {
  border-color: #00aeff;
}

.el-icon.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

:deep(.el-form-item__label) {
    color: #b0bec5; /* 调整标签颜色 */
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
    background-color: #2c2834; /* 输入框背景色 */
    color: #eee; /* 输入框文字颜色 */
    border: 1px solid #444; /* 输入框边框 */
}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
    color: #777; /* 占位符颜色 */
}

/* 解散按钮样式 */
.dissolve-button-container {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #444; /* 分隔线 */
    text-align: right;
}
</style>
